const { User, Resource, Feedback, sequelize } = require('../models');
const { Op } = require('sequelize');

/**
 * 获取个性化推荐资源
 * @route GET /api/home/recommend
 */
const getRecommendations = async (req, res, next) => {
  try {
    const { userId = 1, limit = 5 } = req.query;
    
    // 1. 获取用户信息和偏好
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 获取用户最近使用的资源类型
    const recentResources = await Resource.findAll({
      where: { userId },
      order: [['generateTime', 'DESC']],
      limit: 10
    });
    
    // 统计用户最常使用的资源类型
    const typeCount = {};
    recentResources.forEach(resource => {
      typeCount[resource.type] = (typeCount[resource.type] || 0) + 1;
    });
    
    // 按使用频率排序资源类型
    const preferredTypes = Object.entries(typeCount)
      .sort((a, b) => b[1] - a[1])
      .map(entry => entry[0]);
    
    // 3. 基于用户偏好和历史记录推荐资源
    const recommendations = [];
    
    // 3.1 首先推荐用户偏好风格的资源
    if (user.stylePreference) {
      const stylePreferences = Object.entries(user.stylePreference)
        .filter(([key, value]) => value && key.includes('Style'))
        .map(([key, value]) => value);
      
      if (stylePreferences.length > 0) {
        // 查询符合用户风格偏好的资源
        for (const style of stylePreferences) {
          // 这里简化处理，实际项目中可能需要更复杂的匹配逻辑
          const styleResources = await Resource.findAll({
            where: {
              userId: { [Op.ne]: userId }, // 不包括用户自己的资源
              isSaved: true,
              [Op.or]: [
                { content: { [Op.like]: `%${style}%` } },
                { content: { [Op.like]: `%"style":"${style}"%` } }
              ]
            },
            order: [['generateTime', 'DESC']],
            limit: 2
          });
          
          recommendations.push(...styleResources);
          
          if (recommendations.length >= limit) {
            break;
          }
        }
      }
    }
    
    // 3.2 然后推荐用户常用类型的高质量资源
    if (recommendations.length < limit && preferredTypes.length > 0) {
      for (const type of preferredTypes) {
        // 查询该类型的高质量资源（根据反馈评分）
        const typeResources = await Resource.findAll({
          where: {
            userId: { [Op.ne]: userId }, // 不包括用户自己的资源
            type,
            isSaved: true
          },
          include: [{
            model: Feedback,
            where: { evaluation: 'satisfied' },
            required: true
          }],
          order: [['generateTime', 'DESC']],
          limit: limit - recommendations.length
        });
        
        recommendations.push(...typeResources);
        
        if (recommendations.length >= limit) {
          break;
        }
      }
    }
    
    // 3.3 如果推荐数量不足，补充最新的保存资源
    if (recommendations.length < limit) {
      const latestResources = await Resource.findAll({
        where: {
          userId: { [Op.ne]: userId }, // 不包括用户自己的资源
          isSaved: true,
          id: { [Op.notIn]: recommendations.map(r => r.id) } // 排除已推荐的资源
        },
        order: [['generateTime', 'DESC']],
        limit: limit - recommendations.length
      });
      
      recommendations.push(...latestResources);
    }
    
    // 4. 格式化推荐资源
    const formattedRecommendations = recommendations.map(resource => {
      const baseInfo = {
        id: resource.id,
        type: resource.type,
        generateTime: resource.generateTime
      };
      
      // 根据资源类型提取不同的关键信息
      switch (resource.type) {
        case 'design':
          return {
            ...baseInfo,
            title: resource.content.title || '未命名教学设计',
            objectives: resource.content.objectives || [],
            recommendReason: '符合您喜欢的教学风格'
          };
        case 'image':
          return {
            ...baseInfo,
            imageUrl: resource.content.imageUrl,
            style: resource.content.style,
            recommendReason: '基于您常用的图像风格推荐'
          };
        case 'video':
          return {
            ...baseInfo,
            videoUrl: resource.content.videoUrl,
            duration: resource.content.duration,
            recommendReason: '您可能感兴趣的教学视频'
          };
        case 'exercise':
          return {
            ...baseInfo,
            knowledgePoints: resource.content.knowledgePoints || [],
            totalCount: resource.content.totalCount || 0,
            recommendReason: '高质量的练习题资源'
          };
        case 'paper':
          return {
            ...baseInfo,
            title: resource.content.title || '未命名试卷',
            totalScore: resource.content.totalScore || 100,
            recommendReason: '精选试卷推荐'
          };
        default:
          return {
            ...baseInfo,
            recommendReason: '可能对您有帮助的资源'
          };
      }
    });
    
    // 5. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        recommendations: formattedRecommendations
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户资源统计数据
 * @route GET /api/home/stats
 */
const getUserStats = async (req, res, next) => {
  try {
    const { userId = 1 } = req.query;
    
    // 1. 获取用户信息
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 获取用户资源总数
    const totalResources = await Resource.count({
      where: { userId }
    });
    
    // 3. 获取各类型资源数量
    const resourcesByType = await Resource.findAll({
      attributes: ['type', [sequelize.fn('COUNT', sequelize.col('id')), 'count']],
      where: { userId },
      group: ['type'],
      raw: true
    });
    
    // 4. 获取已保存资源数量
    const savedResources = await Resource.count({
      where: { 
        userId,
        isSaved: true
      }
    });
    
    // 5. 获取最近一周资源生成趋势
    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
    
    const weeklyTrend = await Resource.findAll({
      attributes: [
        [sequelize.fn('DATE', sequelize.col('generateTime')), 'date'],
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      where: { 
        userId,
        generateTime: { [Op.gte]: oneWeekAgo }
      },
      group: [sequelize.fn('DATE', sequelize.col('generateTime'))],
      order: [[sequelize.fn('DATE', sequelize.col('generateTime')), 'ASC']],
      raw: true
    });
    
    // 6. 获取反馈统计
    const feedbackStats = await Feedback.findAll({
      attributes: [
        'evaluation',
        [sequelize.fn('COUNT', sequelize.col('id')), 'count']
      ],
      include: [{
        model: Resource,
        attributes: [],
        where: { userId }
      }],
      group: ['evaluation'],
      raw: true
    });
    
    // 7. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        totalResources,
        savedResources,
        resourcesByType: resourcesByType.reduce((acc, item) => {
          acc[item.type] = parseInt(item.count);
          return acc;
        }, {}),
        weeklyTrend,
        feedbackStats: feedbackStats.reduce((acc, item) => {
          acc[item.evaluation] = parseInt(item.count);
          return acc;
        }, {})
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  getRecommendations,
  getUserStats
};